package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyRongXinDai;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeRongXinDai;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformMultiPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMaskConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 安心分期&融星贷8位全28分
 *
 * @author 江小游
 */
@ApiPlan(productId = "241", type = ApiPlanConvertType.PLAT_PHONE_MASK)
public class ApiPlatRongXinDaiPhoneMask implements ApiPlatformPhoneMaskConvertHandler {
    private static final String KEY = "2835e65fa9c74e1947ff68e45295d85c";
    private static final String CHANNEL = "9hhi2zl";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        //  撞库流程
        ApiPlatDataExchangeRongXinDai apiPlatDataExchange = new ApiPlatDataExchangeRongXinDai();
        // 扩展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiDataExchangeParameter);
        // 姓名
        apiPlatDataExchange.setUserName("浩安星");
        // 手机号掩码
        apiPlatDataExchange.setPhoneMask(apiDataExchangeParameter.getPhoneMask());
        // 城市
        apiPlatDataExchange.setCity(apiDataExchangeParameter.getCity());
        // 年龄
        apiPlatDataExchange.setAge(apiDataExchangeParameter.getAge());
        //  性别 【1】男【2】女
        String sex = ChooseEq.create(apiDataExchangeParameter.getSex())
                .when("0", "1")
                .when("1", "2")
                .end("1");
        apiPlatDataExchange.setSex(sex);
        // 贷款金额【20】以万为单位
        String loanAmount = ChooseEq.create(apiDataExchangeParameter.getLoanAmount())
                .when("1", "3")
                .when("2", "10")
                .when("3", "20")
                .when("4", "30")
                .end();
        apiPlatDataExchange.setLoanAmount(loanAmount);
        // 芝麻分 【0】无【1】600以下 【2】600-649 【3】650-699 【4】700以上
        String sesameCredit = ChooseEq.create(apiDataExchangeParameter.getSesameCredit())
                .when("1", "1")
                .when("2", "2")
                .when("3", "3")
                .when("4", "4")
                .end();
        apiPlatDataExchange.setSesameCredit(sesameCredit);
        // 花呗额度 【0】无 【1】0-5000 【2】5000以上
        String hbLimit = ChooseEq.create(apiDataExchangeParameter.getHbLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "2")
                .when("5", "2")
                .end("0");
        apiPlatDataExchange.setHbLimit(hbLimit);
        // 白条额度 【0】无 【1】0-5000 【2】5000以上
        String btLimit = ChooseEq.create(apiDataExchangeParameter.getBtLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "2")
                .when("5", "2")
                .end("0");
        apiPlatDataExchange.setBtLimit(btLimit);
        // 车 【0】无 【1】有
        apiPlatDataExchange.setCarInfo(String.valueOf(apiFieldConverter.hasCarInfoToNumber()));
        // 房产 【0】无 【1】有
        apiPlatDataExchange.setRealEstateInfo(String.valueOf(apiFieldConverter.hasRealEstateInfoToNumber()));
        // 公积金 【0】无 【1】有
        apiPlatDataExchange.setProvidentFund(String.valueOf(apiFieldConverter.hasProvidentFundToNumber()));
        // 社保缴纳 【0】无 【1】有
        apiPlatDataExchange.setSocialSecurity(String.valueOf(apiFieldConverter.hasSocialSecurityToNumber()));
        // 保险保单 【0】无 【1】有
        apiPlatDataExchange.setInsurancePolicy(String.valueOf(apiFieldConverter.hasInsurancePolicyToNumber()));
        // 营业执照 【0】无 【1】有
        apiPlatDataExchange.setBizLicenseYear(String.valueOf(apiFieldConverter.hasBizLicenseYearToNumber()));
        // 职业 【0】无 【1】公务员 【2】事业单位 【3】民营 【4】国企
        String career = ChooseEq.create(apiDataExchangeParameter.getCareer())
                .when("1", "3")
                .when("2", "0")
                .when("3", "3")
                .when("4", "1")
                .when("5", "3")
                .end("3");
        apiPlatDataExchange.setCareer(career);
        // 我方字典-信用情况（逾期）【0】无【1】当前无逾期 【2】当前有逾期 【3】逾期已结清
        String overdue = ChooseEq.create(apiDataExchangeParameter.getOverdue())
                .when("1", "1")
                .when("2", "2")
                .when("3", "3")
                .end("1");
        apiPlatDataExchange.setOverdue(overdue);
        // 加密
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(apiPlatDataExchange));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channel", CHANNEL);
            newMap.put("content", data);
        });
        return JsonUtils.toJson(map);
    }


    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        // 进件流程
        ApiPlatApplyRongXinDai apiPlatApply = new ApiPlatApplyRongXinDai();
        // 扩展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        // 撞库流水号
        apiPlatApply.setCheck_no(apiApplyParameter.getApplyId());
        // 手机号
        apiPlatApply.setPhone(apiApplyParameter.getPhone());
        // 姓名
        apiPlatApply.setUserName(apiApplyParameter.getUserName());
        // 城市
        apiPlatApply.setCity(apiApplyParameter.getCity());
        // 年龄
        apiPlatApply.setAge(apiApplyParameter.getAge());
        //  性别 【1】男【2】女
        String sex = ChooseEq.create(apiApplyParameter.getSex())
                .when("0", "1")
                .when("1", "2")
                .end("1");
        apiPlatApply.setSex(sex);
        // 贷款金额【20】以万为单位
        String loanAmount = ChooseEq.create(apiApplyParameter.getLoanAmount())
                .when("1", "3")
                .when("2", "10")
                .when("3", "20")
                .when("4", "30")
                .end();
        apiPlatApply.setLoanAmount(loanAmount);
        // 芝麻分 【0】无【1】600以下 【2】600-649 【3】650-699 【4】700以上
        String sesameCredit = ChooseEq.create(apiApplyParameter.getSesameCredit())
                .when("1", "1")
                .when("2", "2")
                .when("3", "3")
                .when("4", "4")
                .end();
        apiPlatApply.setSesameCredit(sesameCredit);
        // 花呗额度 【0】无 【1】0-5000 【2】5000以上
        String hbLimit = ChooseEq.create(apiApplyParameter.getHbLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "2")
                .when("5", "2")
                .end("0");
        apiPlatApply.setHbLimit(hbLimit);
        // 白条额度 【0】无 【1】0-5000 【2】5000以上
        String btLimit = ChooseEq.create(apiApplyParameter.getBtLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "2")
                .when("5", "2")
                .end("0");
        apiPlatApply.setBtLimit(btLimit);
        // 车 【0】无 【1】有
        apiPlatApply.setCarInfo(String.valueOf(apiFieldConverter.hasCarInfoToNumber()));
        // 房产 【0】无 【1】有
        apiPlatApply.setRealEstateInfo(String.valueOf(apiFieldConverter.hasRealEstateInfoToNumber()));
        // 公积金 【0】无 【1】有
        apiPlatApply.setProvidentFund(String.valueOf(apiFieldConverter.hasProvidentFundToNumber()));
        // 社保缴纳 【0】无 【1】有
        apiPlatApply.setSocialSecurity(String.valueOf(apiFieldConverter.hasSocialSecurityToNumber()));
        // 保险保单 【0】无 【1】有
        apiPlatApply.setInsurancePolicy(String.valueOf(apiFieldConverter.hasInsurancePolicyToNumber()));
        // 营业执照 【0】无 【1】有
        apiPlatApply.setBizLicenseYear(String.valueOf(apiFieldConverter.hasBizLicenseYearToNumber()));
        // 职业 【0】无 【1】公务员 【2】事业单位 【3】民营 【4】国企
        String career = ChooseEq.create(apiApplyParameter.getCareer())
                .when("1", "3")
                .when("2", "0")
                .when("3", "3")
                .when("4", "1")
                .when("5", "3")
                .end("3");
        apiPlatApply.setCareer(career);
        // 信用情况（逾期）【0】无【1】当前无逾期 【2】当前有逾期 【3】逾期已结清
        String overdue = ChooseEq.create(apiApplyParameter.getOverdue())
                .when("1", "1")
                .when("2", "2")
                .when("3", "3")
                .end("1");
        apiPlatApply.setOverdue(overdue);
        // 备注
        apiPlatApply.setRemarks(apiApplyParameter.getFormRemark());
        // 加密
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(apiPlatApply));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channel", CHANNEL);
            newMap.put("content", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMaskApply respApply(String respJson) throws Exception {
        //  撞库返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 1)) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        JSONObject resData = jsonObject.getJSONObject("data");
        if (resData == null) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        if (!Eq.object(resData.getInteger("status"), 1)) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        return RespPlatformPhoneMaskApply.ofSuc();
    }

    @Override
    public RespPlatformMultiPhoneMaskDataExchange respDataExchange(String respJson) {
        //  撞库返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 1)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        JSONObject resData = jsonObject.getJSONObject("data");
        if (resData == null) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }

        //  获取属性值
        RespPlatformMultiPhoneMaskDataExchange respPlatformMultiPhoneMaskDataExchange = RespPlatformMultiPhoneMaskDataExchange.ofSuc();
        List<RespPlatformPhoneMaskDataExchange> listRespPlatformPhoneMaskDataExchange = CollUtils.newArrayList();
        if (!Eq.object(resData.getInteger("status"), 1)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        if (ValidParam.isNotNull(resData)) {
            JSONObject resProduct = resData.getJSONObject("product");
            String applyId = resData.getString("check_no");
            BigDecimal price = resProduct.getBigDecimal("price");
            String logo = resProduct.getString("logo_img");
            String companyName = resProduct.getString("organization_name");
            String productName = resProduct.getString("product_name");

            //  获取协议内容
            List<ApiProtocol> protocolList = CollUtils.newArrayList(newList -> {
                //  获取协议
                JSONArray listProtocolResult = resProduct.getJSONArray("feat");
                IteratorUtils.array(listProtocolResult, (protocolResult, index) -> {
                    JSONObject protocolObject = listProtocolResult.getJSONObject(index);
                    ApiProtocol protocol = new ApiProtocol();
                    protocol.setProtocolName(protocolObject.getString("name"));
                    protocol.setProtocolUrl(protocolObject.getString("url"));
                    newList.add(protocol);
                });
            });

            List<String> phoneMd5List = CollUtils.newArrayList(newList -> {
                JSONArray jsonArray = resData.getJSONArray("exist_md5");
                IteratorUtils.array(jsonArray, (protocolResult, index) -> {
                    String phoneMd5  = jsonArray.getString(index);
                    newList.add(phoneMd5);
                });
            });
            //  返回转换内容
            RespPlatformPhoneMaskDataExchange result = RespPlatformPhoneMaskDataExchange.of();

            result.setApplyId(applyId);
            result.setPrice(price);
            result.setLogoPath(logo);
            result.setDisplayName(companyName);
            result.setProductName(productName);
            result.setProtocolList(protocolList);
            result.setListPhoneMd5(phoneMd5List);
            listRespPlatformPhoneMaskDataExchange.add(result);
        }
        respPlatformMultiPhoneMaskDataExchange.setListPhoneMask(listRespPlatformPhoneMaskDataExchange);
        return respPlatformMultiPhoneMaskDataExchange;
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return null;
    }
}
